<template>
  <el-drawer v-model="drawer" :close-on-click-modal="false" :direction="direction">
    <template #header>
      <h4>添加用户</h4>
    </template>
    <template #default>
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto" label-position="top">
        <el-form-item label="用户名" prop="userId">
          <el-input v-model="ruleForm.userId" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="ruleForm.roleId" placeholder="请选择角色" style="width: 100%" @change="handleRoleChange">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <!-- 当选择酒店商家角色时显示酒店名称字段 -->
        <el-form-item label="酒店名称" prop="hotelName" v-if="showHotelField">
          <el-input v-model="ruleForm.hotelName" placeholder="请输入酒店名称"/>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { createUser, getRoleList } from '@/api/user'

const emit = defineEmits(['refresh'])

interface RuleForm {
  userId: string
  email: string
  password: string
  roleId: number
  hotelName?: string
}

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  userId: '',
  email: '',
  password: '',
  roleId: null,
  hotelName: ''
})
const roleList = ref([])

// 计算属性，根据角色ID决定是否显示酒店字段
const showHotelField = computed(() => ruleForm.roleId === 2)

const drawer = ref(false)
const direction = ref('rtl' as 'rtl' | 'ltr' | 'ttb' | 'btt')

// 角色变化时的处理函数
const handleRoleChange = (value: number) => {
  if (value !== 2) {
    // 如果不是酒店商家，清空酒店名称
    ruleForm.hotelName = ''
  }
}

const rules = reactive<FormRules<RuleForm>>({
  userId: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        // 限制用户名长度，避免过长的中文名
        if (value && value.length > 20) {
          callback(new Error('用户名不能超过20个字符'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  hotelName: [{ required: true, message: '请输入酒店名称', trigger: 'blur' }]
})

const submitForm = () => {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      // 确保roleId为数字类型
      const formData = {
        ...ruleForm,
        roleId: Number(ruleForm.roleId) // 确保roleId是数字类型
      };

      // 如果不是酒店商家角色，不提交hotelName字段
      if (formData.roleId !== 2) {
        delete formData.hotelName;
      }

      // 输出提交的数据，用于调试
      console.log('提交的用户数据:', formData);

      createUser(formData).then(res => {
        const result = res.data
        if (result.code === 200 && result.data) {
          ElMessage.success('添加成功')
          handleClose()
          emit('refresh')
        } else {
          ElMessage.error(result.message || '添加失败')
        }
      }).catch(error => {
        console.error('创建用户失败:', error)
        ElMessage.error('网络错误，请稍后重试')
      })
    }
  })
}
const handleClose = () => {
  drawer.value = false
}
const open = () => {
  drawer.value = true
  // 重置表单
  ruleForm.userId = ''
  ruleForm.email = ''
  ruleForm.password = ''
  ruleForm.roleId = null
  ruleForm.hotelName = ''
  
  getRoleList().then(res => {
    const result = res.data
    if (result.code === 200) {
      // 从当前用户信息中获取角色列表
      roleList.value = result.data.roles || []
    }
  })
}
defineExpose({ open })
</script>